<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;


use App\Model\Coupon;
use App\Model\Device;
use Exception;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use App\Model\Distributors;

/**
 * 主页优惠券
 */
class HomeCouponController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    #[Inject]
    protected Coupon $coupon;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**
     * 活动列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function list(RequestInterface $request): ResponseInterface
    {
        try {
            $info = $this->distributors->getInfo($request);
            if (!$info) {
                return $this->error(code: '400', msg: '登录态失效 请重新登录');
            }
            $page = $request->inputs(['page', 'limit', 'is_active', 'type', 'keyword']);
            $model = $this->coupon
                ->when($page['is_active'], function ($query) use ($page) {
                    return $query->where('is_active', $page['is_active']);
                })
                ->when($page['keyword'], function ($query) use ($page) {
                    return $query->where('type', 'like', '%' . $page['keyword'] . '%');
                })
                ->when($page['type'], function ($query) use ($page) {
                    return $query->where('type', Coupon::TYPE_MAP[$page['type']]);
                })
                ->where('distributor_id', $info['id']);
            $data['total'] = $model->count();
            $data['list'] = $model
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit'])
                ->get(['id', 'type', 'fee', 'days', 'content', 'is_active', 'content', 'images', 'start_date', 'end_date'])->toArray();
            $time = time();
            foreach ($data['list'] as $k => $v) {
                $start = strtotime($v['start_date']);
                $end = strtotime($v['end_date']);
                $data['list'][$k]['check_time'] = [];
                if ($time < $start) {
                    $data['list'][$k]['check_time']['label'] = '活动未开始';
                    $data['list'][$k]['check_time']['status'] = 0;
                } elseif ($time > $end) {
                    $data['list'][$k]['check_time']['label'] = '活动已结束';
                    $data['list'][$k]['check_time']['status'] = 1;
                } else {
                    $data['list'][$k]['check_time']['label'] = '活动进行中';
                    $data['list'][$k]['check_time']['status'] = 2;
                }
            }
            return $this->success($data);
        } catch (Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(1002, '操作繁忙 请稍后重试');
        }
    }

    /**
     * 修改活动状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request): ResponseInterface
    {
        $couponId = $request->input('coupon_id');
        $status = $request->input('is_active', 0, 'int');
        if (!$couponId) {
            return $this->error(1001, '优惠券信息不存在');
        }

        $couponModel = $this->coupon->where('id', $couponId)->first();
        if (!$couponModel) {
            return $this->error(1001, '优惠券信息不存在');
        }
        try {
            if ($status > 0) {
                $this->coupon->where('distributor_id', $couponModel->distributor_id)
                    ->where('type', $couponModel->type)
                    ->update(['is_active' => 0]);
            }
            $couponModel->is_active = $status;
            $couponModel->save();
            return $this->success();
        } catch (Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(1002, '操作繁忙 请稍后重试');
        }
    }

    /**
     * 添加营销活动
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function create(RequestInterface $request): ResponseInterface
    {
        try {
            $info = $this->distributors->getInfo($request);
            if (!$info) {
                return $this->error(code: '400', msg: '登录态失效 请重新登录');
            }
            $params = $request->inputs(['id', 'type', 'start_date', 'end_date', 'fee', 'days', 'quantity', 'is_active', 'content', 'images', 'stations', 'moneys']);
            if (isset($params['stations'])) {
                $stations = json_decode($params['stations']);
                $stations = array_unique($stations);
            } else {
                if (!$params['stations']) {
                    $stations = [];
                } else {
                    $stations = $params['stations'];
                }
            }
            unset($params['stations']);
            if (isset($params['moneys'])) {
                $moneys = json_decode($params['moneys'], true);
            } else {
                if (!$params['moneys']) {
                    $moneys = [];
                } else {
                    $moneys = $params['moneys'];
                }
            }
            unset($params['moneys']);
            $params['distributor_id'] = $info['id'];
            $type = $params['type'];
            $params['type'] = Coupon::TYPE_MAP[$params['type']];
            if (isset($params['id']) && $params['id']) {
                $active = Coupon::where('id', $params['id'])->save($params);
            } else {
                $active = Coupon::create($params);
            }
            if (!$active) {
                return $this->error('1003', '创建失败 请稍后重试');
            }
            $cacheKey = Coupon::COUPON_DEVICE_CACHE . $active->id;
            foreach ($stations as $k => $v) {
                $this->redis->sAdd($cacheKey, $v);
            }
            if ($type == Coupon::TYPE_RECHARGE_RECEIVE) {
                $cacheKey = Coupon::COUPON_MONEY_CACHE . $active->id;
                foreach ($moneys as $k => $v) {
                    $this->redis->hSet($cacheKey, (string)$k, $v);
                }
            }
            return $this->success(msg: '添加活动成功');
        } catch (Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(1002, '操作繁忙 请稍后重试');
        }
    }

    /**
     * 活动详情
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function detail(RequestInterface $request): ResponseInterface
    {
        try {
            $info = $this->distributors->getInfo($request);
            if (!$info) {
                return $this->error(code: '400', msg: '登录态失效 请重新登录');
            }
            $couponId = $request->input('coupon_id');
            $couponModel = $this->coupon->where('id', $couponId)->first()->toArray();
            if ($couponModel) {
                $deviceKey = Coupon::COUPON_DEVICE_CACHE . $couponId;
                $couponModel['devices'] = $this->redis->sMembers($deviceKey);
                if ($couponModel['type'] == Coupon::TYPE_MAP[Coupon::TYPE_RECHARGE_RECEIVE]) {
                    $moneyKey = Coupon::COUPON_MONEY_CACHE . $couponId;
                    $couponModel['moneys'] = $this->redis->hGetAll($moneyKey);
                }
            }
            return $this->success($couponModel);
        } catch (Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(1002, '操作繁忙 请稍后重试');
        }
    }

    /**
     * 删除营销
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function del(RequestInterface $request): ResponseInterface
    {
        try {
            $info = $this->distributors->getInfo($request);
            if (!$info) {
                return $this->error(code: '400', msg: '登录态失效 请重新登录');
            }
            $couponId = $request->input('coupon_id', 0, 'int');

            $this->coupon->where('id', $couponId)
                ->where('distributor_id', $info['id'])
                ->delete();
            $deviceKey = Coupon::COUPON_DEVICE_CACHE . $couponId;
            $moneyKey = Coupon::COUPON_MONEY_CACHE . $couponId;
            $this->redis->del($deviceKey);
            $this->redis->del($moneyKey);
            return $this->success(msg: '删除活动成功');
        } catch (Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(1002, '操作繁忙 请稍后重试');
        }
    }

    /**
     * 获取优惠券使用情况
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getCouponCount(RequestInterface $request): ResponseInterface
    {
        $couponId = $request->input('coupon_id', 0, 'int');
        $data['all_people'] = DB::table('coupon_records')
            ->where('coupon_id', $couponId)
            ->select(DB::raw('COUNT(DISTINCT user_id) as count'))
            ->first();

        $data['used_people'] = DB::table('coupon_records')
            ->where('coupon_id', $couponId)
            ->whereNotNull('used_at')
            ->select(DB::raw('COUNT(DISTINCT user_id) as count'))
            ->first();
        $data['used_count']['count'] = DB::table('coupon_records')
            ->where('coupon_id', $couponId)
            ->whereNotNull('used_at')
            ->count();
        return $this->success($data);
    }
}
